package cn.edu.scau.cmi.chenmiaopeng;

import java.io.IOException;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import cn.edu.scau.cmi.chenmiaopeng.controller.compositePattern.*;
import javafx.scene.control.ToggleGroup;
import javafx.scene.control.TreeCell;
import javafx.scene.control.Label;
import javafx.scene.control.RadioButton;
import javafx.scene.control.Toggle;
import javafx.scene.control.TreeView;
import javafx.scene.input.MouseEvent;
import javafx.scene.control.TreeItem;
import javafx.scene.layout.*;
import javafx.scene.text.Text;
public class CompositePatternClient extends Application{
	public static void main(String[] args) {
		launch(args);
	}
	public void start(Stage primaryStage) throws Exception{
		try {
		  FXMLLoader loader = new FXMLLoader(getClass().getResource("/cn/edu/scau/cmi/chenmiaopeng/ui/compositePattern/CompositePatternUI.fxml"));
		  Parent root = loader.load();
		  Scene scene = new Scene(root, 414, 462);
		  primaryStage.setScene(scene);
		  primaryStage.setTitle("组合模式");
		  primaryStage.show();
		  initTree(root);
		  CompositePatternController.setOriginalOrganization();  //初始化根节点：安全模式和透明模式都初始化
		}
		catch(IOException e) {
			e.printStackTrace();
		}
    }
	public void initTree(Parent root){
		@SuppressWarnings("unchecked")
		TreeView<String> treeView = (TreeView<String>)root.lookup("#treeView");
		Label tips = (Label)root.lookup("#tips");
		TreeItem<String> tree_s = new TreeItem<String>("orginal organization");
		CompositePatternController.setTreeItem(tree_s);  //一开始默认是安全模式，所以应将安全模式的树根插入
		tree_s.setExpanded(true);
		treeView.setRoot(tree_s);
		
        TreeItem<String> tree_t = new TreeItem<String>("orginal organization");
//		CompositePatternController.setTreeItem(tree_t);
		tree_t.setExpanded(true);
		//对复合模式控制器设置两种模式（安全、透明模式的）根节点
		CompositePatternController.setOriginalTreeItem(tree_s, tree_t);
		treeView.setPrefSize(200, 200);
		addTreeAction(treeView,tips);
		initToggle(root,treeView,tree_s,tree_t);
	}
	private void addTreeAction(TreeView treeView,Label label) {
		treeView.addEventFilter(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>()    {        
			public void handle(MouseEvent event)        {            
				Node node = event.getPickResult().getIntersectedNode();            
				if (node instanceof Text || (node instanceof TreeCell && ((TreeCell) node).getText() != null)) {                
					String name = (String) ((TreeItem)treeView.getSelectionModel().getSelectedItem()).getValue(); 
					CompositePatternController.setSelectOrgName(name);
					System.out.println("Node click: " + name);  
					label.setText("当前选择的组织是："+name);
					//考虑 选择根节点的情况：
					CompositePatternController.setTreeItem((TreeItem)treeView.getSelectionModel().getSelectedItem());  
					//设置当前选择的树节点,这里不能注释，否则CompositeController更新的子节点都更新在根节点下
			}        
				}    
			});
		
	}
	private void initToggle(Parent root,TreeView<String> treeView,TreeItem<String> tree_s,TreeItem<String> tree_t) {
		ToggleGroup group = new ToggleGroup();
		RadioButton safePattern = (RadioButton)root.lookup("#safePattern");
//				loader.getNamespace().get("safePattern");
		RadioButton transparentPattern = (RadioButton)root.lookup("#transparentPattern");
		safePattern.setUserData("safePattern");
		transparentPattern.setUserData("transparentPattern");
    	safePattern.setToggleGroup(group);
    	transparentPattern.setToggleGroup(group);
    	safePattern.setSelected(true);
    	ChangeListener toogleChangeListener = new ChangeListener<Toggle>() {

			@Override
			public void changed(ObservableValue<? extends Toggle> observable, Toggle oldValue, Toggle newValue) {
				RadioButton tempRd = (RadioButton)newValue;
//				if(tempRd.getText().equals("安全组合模式")) System.out.println("当前选择的按钮是："+tempRd.getText());  //这样输出才是“安全组合模式”
//				System.out.println("当前选择的按钮的用户数据是："+tempRd.getUserData().toString());  //看来还是要另外设userdata，这样才能在监听器里比较，否则报空指针错误
				if(newValue.getUserData().toString().equals("safePattern")) {
//					System.out.println("当前选择安全模式。");
//					if(CompositePatternController.getTreeItem()==tree_t)  不要加这个判断条件，当s模式下有选择节点；而转到t模式下，又没有选择节点而直接操作时，则会引起 操作时找不到节点，所以只要转换模式，则要对nowSelectOrg做根节点转换
						//这是为了对应交叉转变后，用户没有点击选择节点，这时进行操作会导致更新树没有反应，
						//所以凡是转变模式，都应将treeItem设为当前模式下的根节点
					CompositePatternController.setTreeItem(tree_s);
					CompositePatternController.setSelectOrgName(tree_s.getValue());
					treeView.setRoot(tree_s);
				}
				else {
//					System.out.println("当前选择透明模式。");
//					if(CompositePatternController.getTreeItem()==tree_s)  //这是对应初始化时将treeItem设为了tree_s，而用户转变模式后又没有点击选择节点，这时进行操作会导致更新树没有反应，
						//所以凡是转变模式，都应将treeItem设为当前模式下的根节点
					CompositePatternController.setTreeItem(tree_t);
					CompositePatternController.setSelectOrgName(tree_t.getValue());  //tree_t.getValue()即为"orginal organization"
					treeView.setRoot(tree_t);
				}
			}
    		   
    	   };
    	group.selectedToggleProperty().addListener(toogleChangeListener);
    }
}
